package group.raber.jeki.controller;

import group.raber.auth.entity.User;
import group.raber.auth.service.AuthService;
import group.raber.saber.kit.MapKit;
import group.raber.saber.kit.NumberKit;
import group.raber.saber.kit.ValidateKit;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private AuthService authService;

    @RequestMapping(path="/register-action",method = RequestMethod.POST)
    public ModelAndView registerAction(@ModelAttribute User dataUser){
        User user = dataUser;
        //检查用户是否存在
        User existsUser = authService.getUserByCode(dataUser.getCode());
        ValidateKit.isTrue(existsUser==null,"用户[%s]已经存在",dataUser.getCode());

        //注册
        user.setId(NumberKit.nanoTime36());
        authService.saveUser(user);
        authService.updatePassword(user.getId(),user.getPassword());

        return new ModelAndView("views/register-success", MapKit.mapOf("user",user));
//        new ModelAndView("views/register-success", ["user":user]);
    }
    @RequestMapping(path="/logon-action",method = RequestMethod.POST)
    public ModelAndView logonAction(@RequestParam("userCode") String userCode, @RequestParam("password") String password, HttpServletResponse response){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userCode,password);
        subject.login(token);
//        try{
//            subject.login(token);
//        }catch(UnknownAccountException e){
//            response.setStatus(HttpStatus.UNAUTHORIZED.value());
//        }catch(IncorrectCredentialsException e){
//            response.setStatus(HttpStatus.UNAUTHORIZED.value());
//        }

        User user = authService.getUserByCode(userCode);
        return new ModelAndView("redirect:/",MapKit.mapOf("user",user));
//        return new ModelAndView("redirect:/");
    }
}
